<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta content="black" name="apple-mobile-web-app-status-bar-style" />
		<meta content="telephone=no" name="format-detection" />
		<meta content="email=no" name="format-detection" />
		<title>单个终端处理巡检任务</title>
		<link rel="stylesheet" href="../../css/hui.css" />
		<link rel="stylesheet" href="../../css/s_plus.css" />
		<link rel="stylesheet" href="../../css/base.css?time=222" />
		<link rel="stylesheet" href="../../css/layout.css" />
		<link rel="stylesheet" href="../../css/choice.css" />
		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../js/app/api.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
		<script type="text/javascript" src="../../js/control/swal/sweetalert.min.js"></script>
		<link rel="stylesheet" href="../../js/control/swal/sweetalert.css" />
		<link rel="stylesheet" href="../../js/control/select/iosSelect.css">
		<script type="text/javascript" src="../../js/control/select/iosSelect.js"></script>
		<script src="../../js/control/lrz.bundle.js"></script>
<script src="../../js/mui.min.js"></script>
	</head>

	<body>
		<div id="wrapper">
			<header class="f_l maxbox subhead">
				<a class="back" @click="back"><i class="iconfont">&#xe605;</i></a>
				<h1>处理巡检任务</h1>
			</header>
			<section class="f_l maxbox edit_list">


				<ul>
					<li>
						<b>完成量</b>
						<p>已完成 <span class="red">{{resTerminal_checked}}</span> 终端数 <span class="red">{{resTerminal_number}}</span></p>
					</li>
					<!--<li>
      <b>巡检任务</b>
      <p>终端数 <span class="red">{{resTerminal_number}}</span> 个</p>
    </li>-->
				</ul>
				<ul>
					<li>
						<b>所选设备</b>
						<p>
							<a  @click="findDevice2"> 选择设备</a>
						</p>
					</li>
				</ul>
				<div class="txt_list">

					<!--<p><em>设备类型：</em>{{tremInfo.gjType}}</p>-->
					<p><em>设备编号：</em>{{tremInfo.termimalCode}}</p>
					<!--<p><em>设备地址：</em>{{tremInfo.belongStreet}}</p>-->
				</div>
				<h3>设备状态</h3>
				<ul>
					<li>
						<b>设备正常</b>
						<p>
							<a @click="setting('normal')" class="setting" id="normal">设备正常</a>
							
						</p>
					</li>
				</ul>
				<ul>
					<li>
						<b>设备异常</b>
						<p>
							<a @click="setting('error')" class="setting" id="error">设备异常</a>
						</p>
					</li>
				</ul>
		
			</section>
			<!--<section class="f_l maxbox mar_f block">
			<dl>
			    <dt>
			      <h2>描述</h2>
			    </dt>
			    <dd>
			     <textarea v-model="remarks" class="area noEmojiText" name="" cols="" rows=""></textarea> 
			    </dd>
			  </dl>
			</section>-->
			
			<section class="f_l maxbox mar_f block">
				<dl>
					 <dt>
      <h2>上传图片</h2>
    </dt>
					<dd class="photo_list">
						<ul>

							<li v-for="item in imgs"><img :src="item" alt="" /></li>
							<!--<li><img src="../../images/map.jpg" alt="" /></li>
        <li><img src="../../images/map.jpg" alt="" /></li>-->
							<!--<li><a ><i class="iconfont" @click="uploadImg">&#xe626;</i></a></li>-->
							<!--<li><input class="fileControl" id="picture" type="file" accept="image/*" multiple="multiple"></li>-->
							<li>
								
								<a id="selectImgBtn"><i class="iconfont">&#xe626;</i></a>
							</li>
						</ul>
					</dd>
				</dl>
			</section>
			<section class="f_l maxbox mar_t mar_f t_c">
				<a class="btn mian_btn" @click="upload">上传巡检记录</a>

			</section>

		</div>

		</div>

		<script>
			
				function refresh (){
					var tId=localStorage.getItem("Tid");
//					alert(tId);
					sp.tremId=tId;
					var status = false;

					if(sp.zdCodeList!=null&&
						sp.zdCodeList.length>0){
						for (var i=0;i<sp.zdCodeList.length;i++) {
							var cell = sp.zdCodeList[i];
							if(tId==cell.value){
								status=true;
								sp.showDevice(tId);
							}
							
							
						}
						
						if(status){
							hui.toast("您选择的终端编号是:"+tId);

						}else{
							alert("选择的终端 "+tId+",不属于本巡检任务，请重新选择.");
						}
						
						
						
					}
					
				}
			var sp ;
			$(function() {
				
				
				
				

				 sp = new Vue({
					el: "#wrapper",
					data: {
						remarks:"",
						checkType:0,
						checkCount:0,
						imgs:[],
						task: {},
						lists: [],
						resTerminal_number: "",
						resTerminal_checked: "",
						tremId: "",
						taskId: "",
						tremInfo: {},
						status: "",
						zdCodeList: [],//巡检任务下的所有终端
						imgUrl:""
					},
					watch: {
						tremId: function(curVal, oldVal) {

							console.log(curVal);
							this.showDevice(curVal);
						},
					},

					methods: {
						
						
						findDevice2:function(){
							hui.open("findDevice.html?s="+apiManage.getNow(), {}, true, {});
//														hui.open("/modules/terminal/searchDevices.html", {}, true, {});

						},

						setting: function(pid) {

							console.log(pid);
							if(pid == 'normal') {
								$("#normal").css("background", "#ff6c00");
								$("#error").css("background", "#00aef3");
								sp.status = "1";
							} else {
								$("#error").css("background", "#ff6c00");
								$("#normal").css("background", "#00aef3");
								sp.status = "0";
							}
							console.log(sp.status);
						},

						showDevice: function(pid) {
							for(var i = 0; i < sp.lists.length; i++) {

								var cell = sp.lists[i];
								if(pid == cell.termimalCode) {

									sp.tremInfo = cell;

								}
							}
						},
						selectDevice: function() {
							//					  		$("#pop_txt1").selectCity("#pop_box1");

						},
						upload: function() {
							upload();
						},
						back: function() {
								hui.BackDo = function() {
						var current = plus.webview.currentWebview();
						var openCurrent = current.opener();
						if(openCurrent) {
							console.log("调用上一个页面刷新:" + openCurrent.id);
							openCurrent.evalJS("refresh()");
						}
						
						return true;
						
					}
												hui.back();
	
						},

						showStatus: function(status) {

							if(status == '0') {
								return "无告警	";
							} else if(status == '1') {
								return "一般告警";
							} else if(status == '2') {
								return "严重告警";
							} else {
								return "工单处理";

							}
						},

						geshi: function(param) {
							return formatTime(param);
						},
						showType: function(param) {
							//							0：日巡检 1：周巡检 2：月巡检
							if(param == '0') {
								return "日巡检";
							} else if(param == '1') {
								return "周巡检 ";
							} else {
								return "月巡检";

							}
						},
						showState: function(param) {
							//								0下发 1接收 2处理
							if(param == '0') {
								return "下发";
							} else if(param == '1') {
								return "接收";
							} else {
								return "处理";

							}
						}

					}

				});
				
		

				detail();
				//巡检详情
				function detail() {
					hui.loading();
					var zdCode = localStorage.getItem("zdCode");
					sp.tremId = zdCode;
					var taskId = localStorage.getItem("taskId");
					sp.taskId = taskId;
					var username = localStorage.getItem("username");
					var sec = localStorage.getItem("sec_pwd");
					var time = apiManage.getNow();
					var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
					var paramKey = hex_md5(key);
					var jsonParam = JSON.stringify({
						loginName: username,
						time: time,
						key: paramKey
					});

					//   console.log("jsonParam:  "+jsonParam);

					var path = urlManager.inspection_detail() + "?taskId=" + taskId;
					//				   console.log("path:  "+path);
					$.ajax({
						type: "GET",
						url: path,
						beforeSend: function(request) {
							request.setRequestHeader("loginName", username);
							request.setRequestHeader("time", time);
							request.setRequestHeader("sign", paramKey);
							request.setRequestHeader("Content-Type", "application/text");

						},
						success: function(result) {
							hui.closeLoading();
							console.log("巡检详情:" + JSON.stringify(result));
							sp.resTerminal_checked = result.resTerminal_checked;
							sp.resTerminal_number = result.resTerminal_number;
							console.log("sp.resTerminal_checked" + sp.resTerminal_checked);
							console.log("sp.resTerminal_number" + sp.resTerminal_number);

							sp.task = result.checkTask;
							sp.lists = result.resTerminals;

							if(result.resTerminals != null) {
								for(var i = 0; i < result.resTerminals.length; i++) {
									var cell = result.resTerminals[i];
									sp.zdCodeList.push({
										id: cell.termimalCode,
										value: cell.termimalCode
									});
								}
							}
							console.log("sp.zdCodeList-------" + JSON.stringify(sp.zdCodeList))

//							loadSelectData();
							console.log("sp.lists" + JSON.stringify(sp.lists));


//							showDevice(zdCode);
						}

					});

				}

				//选中终端显示对应详情
				function showDevice(pid) {
					for(var i = 0; i < sp.lists.length; i++) {

						var cell = sp.lists[i];
						if(pid == cell.termimalCode) {

							sp.tremInfo = cell;

						}
					}
				}

				function loadSelectData() {
//					var showBankDom = document.querySelector('#selectDevice');
					var bankIdDom = document.querySelector('#bankId');
					showBankDom.addEventListener('click', function() {
						var bankId = showBankDom.dataset['id'];
						var bankName = showBankDom.dataset['value'];

						var bankSelect = new IosSelect(1, [sp.zdCodeList], {
							container: '.container',
							title: '终端选择',
							itemHeight: 50,
							itemShowCount: 5,
							oneLevelId: bankId,
							callback: function(selectOneObj) {
								console.log("   string    " + JSON.stringify(selectOneObj));

								sp.tremId = selectOneObj.value;
								//                  bankIdDom.value = selectOneObj.id;
								//                  showBankDom.innerHTML = selectOneObj.value;
								//                  showBankDom.dataset['id'] = selectOneObj.id;
								//                  showBankDom.dataset['value'] = selectOneObj.value;
							}
						});
					});

				}

				//	upload();
				//上传巡检记录
				function upload() {
//										var zdCode = localStorage.getItem("zdCode");

					if(sp.status == "") {
						swal("", "请先选择设备状态", "warning");

						return;
					}
					if(sp.tremId==null||sp.tremId == "") {
						swal("", "请先选择设备", "warning");

						return;
					}
					
//						if(sp.remarks==null||sp.remarks == "") {
//						swal("", "请填写备注", "warning");
//
//						return;
//					}


					var taskId = localStorage.getItem("taskId");

					var username = localStorage.getItem("username");
					var sec = localStorage.getItem("sec_pwd");
					var time = apiManage.getNow();
					var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
					var paramKey = hex_md5(key);
					var jsonParam = JSON.stringify({
						loginName: username,
						time: time,
						key: paramKey
					});

                  hui.loading("");
					var path = urlManager.mobileExeCheckTask() ;
					var params = {taskId: taskId,tremId:sp.tremId,status:sp.status,imgUrl:sp.imgUrl,remarks:sp.remarks};
					console.log("参数-----"+JSON.stringify(params));
					
//					return;
					$.ajax({
						type: "GET",
						url: path,
						data:params,
						beforeSend: function(request) {
							request.setRequestHeader("loginName", username);
							request.setRequestHeader("time", time);
							request.setRequestHeader("sign", paramKey);
							request.setRequestHeader("Content-Type", "application/text");

						},
						success: function(result) {
									hui.closeLoading();

                      if(result.error_code=='-1'){
                      	swal({  
									title: result.error_msg,
									  text: "",
									  type: "error",
									  showCancelButton: false,
									  confirmButtonColor: "#DD6B55",
									  confirmButtonText: "确认",
									  cancelButtonText: "取消",
									  closeOnConfirm: true,
									  closeOnCancel: false
								},
								function(isConfirm) {  
									if(isConfirm) {
									//	hui.open("inspection_map.html", {}, true, {});
										  
									} else {
										
										  }
								});
                      }
                      else{
                      	swal({  
									title: "成功上传巡检记录",
									  text: "",
									  type: "success",
									  showCancelButton: false,
									  confirmButtonColor: "#DD6B55",
									  confirmButtonText: "确认",
									  cancelButtonText: "取消",
									  closeOnConfirm: true,
									  closeOnCancel: false
								},
								function(isConfirm) {  
									if(isConfirm) {
//										hui.open("inspection_map.html", {}, true, {});
										
											hui.BackDo = function() {
						var current = plus.webview.currentWebview();
						var openCurrent = current.opener();
						if(openCurrent) {
							console.log("调用上一个页面刷新:" + openCurrent.id);
							openCurrent.evalJS("refresh()");
						}
						
						return true;
						
					}
												hui.back();
										
//										hui.back();
//										loadDetail();
										  
									} else {
										
										  }
								});
                      }
							

							console.log("处理巡检任务-单终端:" + JSON.stringify(result));
							//			    			alert('');
							//									sp.lists = result.data;
						}

					});

				}
				
				
					//完成巡检
			function finishTask() {
				
				if(sp.checkType=='1'){
					if(sp.checkCount>sp.resTerminal_checked){
//						alert("抽检数为:"+sp.checkCount+",已完成为:"+sp.resTerminal_checked+",不能完成巡检任务！");
						swal("暂不能完成巡检任务", "抽检数为:"+sp.checkCount+",  已完成:"+sp.resTerminal_checked+" 个终端巡检", "error");
			
						
						return;
					}
				}
				
				
				

				var taskId = localStorage.getItem("taskId");

				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				var paramKey = hex_md5(key);
				var jsonParam = JSON.stringify({
					loginName: username,
					time: time,
					key: paramKey
				});
				console.log("jsonParam:  " + jsonParam);

				var path = urlManager.inspection_Finish() + "?taskId=" + taskId;
				console.log("path:  " + path);
//				<p>已完成 <span class="red">{{resTerminal_checked}}</span> 终端数 <span class="red">{{resTerminal_number}}</span></p>
				
				
				
				var sx=sp.resTerminal_number-sp.resTerminal_checked;
					swal({  
								title: "还有"+sx+"个终端未完成巡检,确认要提交么",
								  text: "",
								  type: "warning",
								  showCancelButton: true,
								  confirmButtonColor: "#DD6B55",
								  confirmButtonText: "确认",
								  cancelButtonText: "取消",
								  closeOnConfirm: true,
								  closeOnCancel: true
							},
							function(isConfirm) {  
								if(isConfirm) {
//									hui.open("inspection_list.html?time" + apiManage.getNow(), {}, true, {});  
//								  alert('点了确认');
//								  return;
								  
												  	
								$.ajax({
									type: "GET",
									url: path,
									beforeSend: function(request) {
										request.setRequestHeader("loginName", username);
										request.setRequestHeader("time", time);
										request.setRequestHeader("sign", paramKey);
										request.setRequestHeader("Content-Type", "application/text");
									},
									success: function(result) {
										console.log("巡检已完成 :  " + JSON.stringify(result));
				
										swal({  
												title: result.error_msg,
												  text: "",
												  type: "success",
												  showCancelButton: false,
												  confirmButtonColor: "#DD6B55",
												  confirmButtonText: "确认",
												  cancelButtonText: "取消",
												  closeOnConfirm: true,
												  closeOnCancel: false
											},
											function(isConfirm) {  
												if(isConfirm) {
														//console.log("提交执行到这里了");
//														return;
//													hui.open("inspection_list.html?time" + apiManage.getNow(), {}, true, {});  
				
											loadDetail();
				
												} else { 
													console.log("提交取消");
				
													 }
											});
				
									}
				
								});
								
								
							
				
								  
								} else { 
//									 alert('点了取消');
//									return;
							}
							});


				
			
			}
				
				
				
			//上传图片相关代码
					function settingImgs(imgList) {

					var newUrl = imgList[0];
					if(sp.imgs != null || sp.imgs.length > 0) {
						if(sp.imgs.length < 3) {
							sp.imgs.push(newUrl);

						} else {
							sp.imgs.splice(0, 1, newUrl);

						}
					} else {
						sp.imgs.push(newUrl);
						console.log(newUrl);
					}

					//							alert(sp.imgs.splice(","));
					sp.imgUrl = sp.imgs.join(",");

					console.log("sp.params.url----" + sp.imgUrl);
					console.log("sp.imgs--" + JSON.stringify(sp.imgs));

				}

				document.getElementById('selectImgBtn').addEventListener('tap', function() {
					if(mui.os.plus) {
						var a = [{
							title: "拍照"
						}, {
							title: "从手机相册选择"
						}];
						plus.nativeUI.actionSheet({
							title: "选择照片",
							cancel: "取消",
							buttons: a
						}, function(b) { /*actionSheet 按钮点击事件*/
							switch(b.index) {
								case 0:
									break;
								case 1:
									getImage(); /*拍照*/
									break;
								case 2:
									galleryImg(); /*打开相册*/
									break;
								default:
									break;
							}
						})
					}
				}, false);

				//拍照上传
				//拍照 
				function getImage() {
					var c = plus.camera.getCamera();
					c.captureImage(function(e) {
						plus.io.resolveLocalFileSystemURL(e, function(entry) {
							var s = entry.toLocalURL() + "?version=" + new Date().getTime();
							uploadHead(s); /*上传图片*/
						}, function(e) {
							console.log("读取拍照文件错误：" + e.message);
						});
					}, function(s) {
						console.log("error" + s);
					}, {
						filename: "_doc/head.png"
					})
				}

				//从相册选图上传
				//本地相册选择 
				function galleryImg() {
					// 从相册中选择图片
					plus.gallery.pick(function(e) {
						for(var i in e.files) {
							var fileSrc = e.files[i]
							//	    	setHtml(fileSrc);
							console.log(fileSrc);
							uploadHead(fileSrc);
						}
					}, function(e) {
						console.log("取消选择图片");
					}, {
						filter: "image",
						multiple: true,
						maximum: 3,
						system: false,
						onmaxed: function() {
							plus.nativeUI.alert('最多只能选择3张图片');
						}
					});

				}

				//图片上传和压缩
				//上传头像图片 
				function uploadHead(imgPath) {
					console.log("imgPath = " + imgPath);
					//          mainImage.src = imgPath; 
					//          mainImage.style.width = "60px"; 
					//          mainImage.style.height = "60px"; 

					var image = new Image();
					image.src = imgPath;
					image.onload = function() {
						var imgData = getBase64Image(image);
						/*在这里调用上传接口*/

						hui.loading("图片上传中...");

						var username = localStorage.getItem("username");
						var sec = localStorage.getItem("sec_pwd");
						var time = apiManage.getNow();
						var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
						var paramKey = hex_md5(key);
						var jsonParam = JSON.stringify({
							loginName: username,
							time: time,
							key: paramKey
						});

						var path = urlManager.uploadFile();
						console.log("path-------" + path);

						var form = new FormData();
						//console.log("base64----"+base64String);
						form.append("imgCode", imgData);
						$.ajax({
							type: "POST",
							url: path,
							data: form,
							contentType: false, // 注意这里应设为false
							processData: false, //false
							beforeSend: function(request) {
								request.setRequestHeader("loginName", username);
								request.setRequestHeader("time", time);
								request.setRequestHeader("sign", paramKey);
							},
							success: function(data) {
								console.log("return data-------------" + JSON.stringify(data));
								var imgList = data.pathlist;
								hui.closeLoading();
								settingImgs(imgList);
							}
						});

					}
				}
				//将图片压缩转成base64 
				function getBase64Image(img) {
					var canvas = document.createElement("canvas");
					var width = img.width;
					var height = img.height;

					var settingWH = 500; //限制宽高 
					// calculate the width and height, constraining the proportions 
					if(width > height) {
						if(width > settingWH) {
							height = Math.round(height *= settingWH / width);
							width = settingWH;
						}
					} else {
						if(height > settingWH) {
							width = Math.round(width *= settingWH / height);
							height = settingWH;
						}
					}
					canvas.width = width; /*设置新的图片的宽度*/
					canvas.height = height; /*设置新的图片的长度*/
					var ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height); /*绘图*/
					var dataURL = canvas.toDataURL("image/png", 0.8);
					return dataURL.replace("data:image/png;base64,", "");
				}
				
				
				

			
			});
		</script>
	</body>

</html>